import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import store from '../store'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: '/api/v1', // api的base_url
  timeout: 15000 // 请求超时时间MessageBox
})

service.defaults.transformRequest = [function (data) {
  //数据序列化
  return qs.stringify(data);
}
];
service.defaults.headers.Accept = 'application/*';

service.interceptors.request.use(function (config) {
  //配置config
  // config.headers.Accept = 'application/*';
  // config.headers.System = 'vue';
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.head.returnCode !== 0) {
      Message({
        message: res.head.returnMsg,
        type: 'error',
        duration: 2 * 1000
      })

      if(res.head.returnCode===110101){
        router.push({ path: '/login' })
      }

    } else  if(res.head.subCode!==0){
      Message({
        message: res.head.subMsg,
        type: 'error',
        duration: 2 * 1000
      })

      return response.data
    }else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
